const db = wx.cloud.database()
const pics = db.collection('pics')
const votes = db.collection('votes')
const $ = db.command.aggregate
Page({
    data: {
        maxvote: 3 //投票次数
    },
    async onLoad(option) {

        let res = await wx.cloud.callFunction({
            name:'getPics'
        })
        
        console.log('getpics',res)
        let plist = res.result.plist
        console.log('plist',plist)

        res = await wx.cloud.callFunction({
            name: 'login'
        })
        console.log('login', res)
        //获取图片id判断投票次数
        let openid = res.result.openid
        let voted = false
        let votedsum = 0
        let today = new Date() //获取今天的日期
        today = today.toJSON().slice(0, 10)
        console.log('today',today)     
        
        res=await votes.aggregate()//当前用户当天投的票数
                       .match({
                           _openid:openid
                       })
                       .project({
                           _openid:1,
                           'date':$.dateToString({
                               date:'$date',
                               format:'%Y-%m-%d'
                           })
                       })
                       .match({
                           date:today
                       })
                       .group({
                           _id:'$_openid',
                           count:$.sum(1)
                       })
                       .end()
        console.log('res',res)
        votedsum = res.list[0]?.count
        console.log('votedsum',votedsum)
        if(isNaN(votedsum)){
            votedsum=0
        }
        this.setData({
            plist,votedsum
        })
        //有图片数据就统计图片有多少张
        if (option.fileid) {
            let current = plist.findIndex(v => {
                return v.fileid == option.fileid
            })
            this.setTitleBer(current)
            this.setData({
                current
            })
        } else {
            this.setTitleBer(0)
        }
    },
    //长按调用此函数上传图片
    async long() {
        let res = await wx.chooseImage({
            count: 1,
        })
        console.log(res)
        let filename = res.tempFilePaths[0]
        let purfilename = filename.split('/').slice(-1)[0]
        res = await wx.cloud.uploadFile({
            cloudPath: 'image/' + purfilename,
            filePath: filename,
        })
        let fileid = res.fileID
        res = await pics.add({
            data: {
                fileid
            }
        })
        if (res.errMsg.indexOf('ok') > -1) {
            wx.showToast({ //toast 提示
                title: '图片插入成功',
                duration: 1000,
                success: function () { //提示成功1000毫秒后再重新跳转
                    setTimeout(function () {
                        wx.navigateTo({
                            url: '/pages/work16/index?fileid=' + fileid,
                        })
                    }, 1000);
                }
            })
        }
    },
    async tap(e) {
        if(this.data.votedsum>=this.data.maxvote){
            wx.showToast({
              title: '超过投票次数',
              icon:'error'
            })
            return
        }
        console.log(e)
        let fileid = e.currentTarget.dataset.id
        let res = await votes.add({
            data: {
                fileid,
                date: db.serverDate()
            }
        })
        console.log(res)
        if(res.errMsg.indexOf('ok')>-1){
            wx.showToast({    //计算还有多少次机会 因为调用会慢一个数值所以再减去1
              title: '还有'+(this.data.maxvote-this.data.votedsum-1)+'次投票机会',
              icon: 'none',
              duration:1000, 
              success: function () {
                setTimeout(function() {
                  wx.navigateTo({
                    url: '/pages/work16/index?fileid='+fileid,
                  })
                }, 1000);
              },
            })
            
        }else{
            wx.showToast({
              icon:'error	',
              title: '投票失败',
            })
        }
    },
    setTitleBer(current) {
        wx.setNavigationBarTitle({
            title: current + 1 + '/' + this.data.plist.length + '  ' +
                this.data.plist[current].count + '票',
        })
    },
    change(e) {
        console.log(e)
        this.setTitleBer(e.detail.current)
    }
})